/*
 * 操作cookie
 * author:恩周
 * modifyTime:2019-12
 */
interface ICookie {
    name: string, // cookie名称
    value: string, // cookie值
    domain: string, // cookie域名
    expires: string // cookie存在时间 默认7天
}
type ISetCookieParams = Array<ICookie>

const Cookie = {
    /*
     * 遍历cookie列表
     * @return string keys 每个cookie的键名
     */
    _eachCookie: function () {
        let list = document.cookie
        // eslint-disable-next-line no-useless-escape
        let keys = list.match(/[^ =;]+(?=\=)/g)
        return keys
    },
    _getExpires: function (expires: string) {
        let str = expires.substr(0, 1);
        let time = parseInt(expires.substr(1, expires.length));
        if (str === 'd') {
            return time * 24 * 3600 * 1000;
        } else if (str === 'h') {
            return time * 3600 * 1000;
        } else if (str === 's') {
            return time * 1000;
        }
    },
    // 获取指定名称cookie的值
    get: function (name: string) {
        let arr = document.cookie.match(new RegExp('(^| )' + name + '=([^;]*)(;|$)'))
        if (arr != null) {
            return unescape(arr[2])
        }
        return null
    },
    /*
     * 设置cookie
     *
     * @param array item cookie键值对{name:"token", value:"ERTYU89OPLKJ", expires:"h50"}
     * 说明：expires属性的值s50:表示50秒，h50:表示50小时，d50:表示50天
     *
     */
    set: function (item: ISetCookieParams) {
        let len = item.length
        let expires: number = 0;
        for (let i = 0; i < len; i++) {
            let name = item[i].name
            let value = item[i].value
            let ret = ''
            if (item[i].expires) {
                expires = this._getExpires(item[i].expires) || 7; // 默认七天
                let date = new Date()
                date.setTime(date.getTime() + expires)
                ret = ';expires=' + new Date(date)
            }
            if (!item[i].domain) {
                ret = name + '=' + value + ';path=/' + ret
            } else {
                ret = name + '=' + value + ';domain=' + item[i].domain + ';path=/' + ret
            }
            document.cookie = ret
        }
    },
    /*
     * 删除指定名称的cookie
     *
     * @param string name cookie键名
     * @param string domain 保存cookie的域
     *
     */
    del: function (name: string, domain: string = '') {
        let exp = new Date()
        exp.setTime(exp.getTime() - 1)
        // (exp);
        let cval = this.get(name)
        if (cval != null) {
            let ret = `${name}=${cval};path=/;expires=${new Date(exp)}`;
            if (domain) {
                ret += `;domain=${domain}`
            }
            document.cookie = ret
        }
    },
    // 清除所有cookie
    clear: function () {
        let keys = this._eachCookie()
        if (keys) {
            for (let i = 0; i < keys.length; i++) {
                this.del(keys[i])
            }
        }
    }
}
export default Cookie
